<?php

namespace app\controller;

use app\service\UserService;
use support\Response;

//登录控制器
class LoginController extends Base
{

    /**
     * 不需要登录的方法
     */
    protected array $noNeedLogin = ['index'];

    //登录
    public function index(): Response
    {
        //获取参数code
        $code = $this->request->post('code', '10001');
        //获取参数platform
        $platform = $this->request->post('platform', 0);
        //昵称
        $nickname = $this->request->post('nickname', '测试用户_' . rand(1000, 10000));
        //头像
        $avatar = $this->request->post('avatar', 'https://ylgys.vip.hnhxzkj.com/wenzhouwaixing.jpg');

        // 启动事务
        $this->db::startTrans();

        try {
            $userService = new UserService();
            $res = $userService->toLoginByCode($code, $platform, $nickname, $avatar);

            if (!empty($res['code']) && $res['code'] == 1) {
                $token = $res['data']['token'];
                if (!$token) {
                    $this->db::rollBack();
                    return json(apiError('登录失败'));
                }
                $this->db::commit();
            } else {
                $this->db::rollBack();
            }
            return json($res);

        } catch (\Exception $e) {
            $this->db::rollBack();
            throw $e;
        }
    }

}
